from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers

from article.search_indexes import ArticleIndex
from users.models import Channel, Article, Label, User, Comment

from users.serializers import UserViewSerializer


class LabelsModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'


class ArticlesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title']


# 文章详情--作者信息(后面通用)
class ArticleUserSerializer(serializers.ModelSerializer):
    articles = ArticlesSerializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'avatar', "articles", 'fans']


class SubSerializer(serializers.ModelSerializer):
    user = ArticleUserSerializer(read_only=True)
    subs = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Comment
        fields = '__all__'


# 文章详情--评论
class CommentsSerializer(serializers.ModelSerializer):
    user = ArticleUserSerializer(read_only=True)
    subs = SubSerializer(many=True, read_only=True)

    class Meta:
        model = Comment
        fields = '__all__'
        # 单独设置父评论不必传
        extra_kwargs = {
            'parent': {'required': False}
        }

    def validate(self, attrs):
        attrs['user'] = self.context['request'].user
        return attrs

    def create(self, validated_data):
        # 创建评论
        comment = super().create(validated_data)
        # 给评论的文章的总评论数 +1
        comment.article.comment_count += 1
        # 保存
        comment.save()
        return comment


# 文章-获取所有频道
class ChannelsModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Channel
        fields = ['id', 'name']


# 文章列表
class ArticleChannelSerializer(serializers.ModelSerializer):
    user = UserViewSerializer()

    # collected = serializers.SerializerMethodField()
    class Meta:
        model = Article
        # fields = "__all__"
        exclude = ('updatetime', 'thumbup', 'comment_count', 'channel', 'labels')

    def get_collected(self, obj: Article):
        # 当前登录用户
        user = self.context.get('request').user
        if user.is_authenticated and (obj in user.collected_articles.all()):
            return True
        else:
            return False


# 文章详情
class ArticleRetrieveSerializer(serializers.ModelSerializer):
    user = ArticleUserSerializer(read_only=True)  # 文章作者信息(后面通用)
    comments = CommentsSerializer(many=True, read_only=True)

    class Meta:
        model = Article
        fields = '__all__'


# 文章发布
class ArticleCreateSerializer(serializers.ModelSerializer):
    image = serializers.CharField(default='', required=False, allow_blank=True)

    class Meta:
        model = Article
        fields = ('content', 'labels', 'title', 'channel', 'image')

    def create(self, validated_data):
        validated_data.update({'user': self.context.get('request').user})
        instance = super().create(validated_data)
        return instance

# 搜索

class ArticleIndexSerializer(HaystackSerializer):
    class Meta:
        index_classes = [ArticleIndex]
        # text 由索引类进行返回, object 由序列化类进行返回,第一个参数必须是text
        fields = ['text', 'id', 'title', 'createtime', 'content']